package de.jeeyeon;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity 
{
	private EditText loginfield;
	private EditText passwordfield;
	private CheckBox checkbox;
	private Button button;
	
	public static final String URL = "http://snuk87.sn.funpic.de/login.php";
	public static final String PREFS_NAME = "LoginFile";
	
	//progessbar
	ProgressDialog progressbar;
	private int progressbarstatus = 0;
	private Handler progressbarhandler = new Handler();
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		loginfield = (EditText) findViewById(R.id.textfield_login);
		
		passwordfield = (EditText) findViewById(R.id.textfield_password);
		
		checkbox = (CheckBox) findViewById(R.id.checkbox_save);
		
		button = (Button) findViewById(R.id.button_login);
		
		setButtonListener();
		
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String name = settings.getString("login", "");
		String pw = settings.getString("password", "");
		
		loginfield.setText(name);
		passwordfield.setText(pw);
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void Progressbar()
	{
		progressbar = new ProgressDialog(this);
		progressbar.setCancelable(true);
		progressbar.setMessage("Logging in ...");
		progressbar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressbar.setProgress(0);
		progressbar.setMax(100);
		progressbar.show();
		
		progressbarstatus = 0;
		
		new Thread(new Runnable() 
		{
			  public void run() 
			  {
				while (progressbarstatus < 100) 
				{
				  progressbarhandler.post(new Runnable() 
				  {
					public void run() 
					{
					  progressbar.setProgress(progressbarstatus);
					}
				  });
				}

				if (progressbarstatus >= 100) 
				{
					// close the progress bar dialog
					progressbar.dismiss();
				}
			  }
		 }).start();
	}
	
	private void setButtonListener()
	{
		button.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View arg0) 
			{
				Progressbar();
				sendLogin();
			}
		});
	}
	private void sendLogin()
	{
		if(passwordfield.getText().toString().equals("") || loginfield.getText().toString().equals(""))
		{
			Toast.makeText(this, "Enter your data!", Toast.LENGTH_LONG).show();
		}
		else
		{
			if(checkbox.isChecked())
			{
				saveLogin();
			}
			
			new AsyncTask<String, Void, String>() 
			{
				@Override
				protected String doInBackground(String... urls) 
				{
					String output = null;
					try{
						
						progressbarstatus = 10;
						DefaultHttpClient httpClient = new DefaultHttpClient();
						HttpPost httpPost = new HttpPost(URL);
						
						progressbarstatus = 25;
						
				        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				        nameValuePairs.add(new BasicNameValuePair("login", loginfield.getText().toString()));
				        nameValuePairs.add(new BasicNameValuePair("password", passwordfield.getText().toString()));
				        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        
				        progressbarstatus = 40;
				        
						HttpResponse httpResponse = httpClient.execute(httpPost);
						HttpEntity httpEntity = httpResponse.getEntity();
						output = EntityUtils.toString(httpEntity);
						
						progressbarstatus = 70;
						
						int index = output.indexOf("<!");
						output = output.substring(0, index);
						
						progressbarstatus = 85;
					}
					catch(Exception e){}
					
					return output;
				}
				
				protected void onPostExecute(String result)
				{	
					if(result.equals("true"))
					{
						Intent i = new Intent(MainActivity.this, FirstActivity.class);
						i.putExtra("author", loginfield.getText().toString().trim());
						progressbarstatus = 100;
						startActivity(i);
					}
					else{
						Toast.makeText(getApplicationContext(), "Wrong Login or Password", Toast.LENGTH_LONG).show();
					}
				}

			}.execute();
		}
	}
	
	public void saveLogin()
	{
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		
		editor.putString("login", loginfield.getText().toString());
		editor.putString("password", passwordfield.getText().toString());
		
		editor.commit();	
	}
}
